import 'package:bitsdojo_window/bitsdojo_window.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/get_user_info_entity.dart';
import 'package:flutter_deer/generated/assets.dart';
import 'package:flutter_deer/ui/cashier/cashier_page.dart';
import 'package:flutter_deer/ui/cashier/provider/turn_shift_provider.dart';
import 'package:flutter_deer/ui/live/gun_live_page.dart';
import 'package:flutter_deer/ui/member/member_page.dart';
import 'package:flutter_deer/ui/order/order_page.dart';
import 'package:flutter_deer/ui/setting/setting_page.dart';
import 'package:flutter_deer/util/log/log_viewer_dialog.dart';
import 'package:get/get.dart';
import 'package:sidebarx/sidebarx.dart';
import 'package:window_manager/window_manager.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with WindowListener {
  final _controller = SidebarXController(selectedIndex: 0, extended: true);
  final _key = GlobalKey<ScaffoldState>();

  bool _isAlwaysOnTop = false;
  String name = '';

  @override
  void initState() {
    super.initState();
    // 确保窗口管理器初始化完成
    _initWindowManager();
    name = GetUserInfoEntity.get()?.loginMerchantName ?? '';
    // _hideStatusBar();
  }

  // 初始化窗口管理器
  Future<void> _initWindowManager() async {
    // 必须在使用windowManager前等待初始化完成
    await windowManager.ensureInitialized();

    // 设置窗口监听器
    windowManager.addListener(this);
  }

  // 切换窗口置顶状态
  Future<void> _toggleAlwaysOnTop() async {
    try {
      final newValue = !_isAlwaysOnTop;
      // 先设置窗口置顶状态
      await windowManager.setAlwaysOnTop(newValue);
      // 成功后再更新UI状态
      setState(() {
        _isAlwaysOnTop = newValue;
      });
    } catch (e) {
      // 处理可能的异常
      print('设置窗口置顶状态失败: $e');
    }
  }

  // 隐藏系统状态栏
  Future<void> _hideStatusBar() async {
    // await FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_FULLSCREEN);
    await windowManager.setTitleBarStyle(TitleBarStyle.hidden);
  }

  // 显示菜单对话框
  void _showMenu() {
    showDialog<void>(
      context: context,
      builder: (context) => const AlertDialog(
        title: Text('应用菜单'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(title: Text('设置')),
            ListTile(title: Text('关于')),
            ListTile(title: Text('帮助')),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isSmallScreen = MediaQuery.of(context).size.width < 600;
    return Scaffold(
      key: _key,
      appBar: isSmallScreen
          ? AppBar(
              backgroundColor: canvasColor,
              title: Text(_getTitleByIndex(_controller.selectedIndex)),
              leading: IconButton(
                  onPressed: () {
                    _key.currentState?.openDrawer();
                  },
                  icon: const Icon(Icons.menu)))
          : null,
      drawer: _LeftSidebar(controller: _controller),
      body: Column(children: [
        // 自定义标题栏
        Container(
          height: 50,
          color: Colors.blue[700],
          child: WindowTitleBarBox(
            child: Row(
              children: [
                // 左侧：应用名称和头像
                Expanded(
                  child: MoveWindow(
                    child: Row(
                      children: [
                        const SizedBox(width: 16),
                        CircleAvatar(radius: 16, child: Image.asset(Assets.imagesIcLauncher)),
                        const SizedBox(width: 8),
                        Text(name, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
                      ],
                    ),
                  ),
                ),

                // 右侧：自定义按钮和窗口控制按钮
                Row(
                  children: [
                    // 菜单按钮
                    // IconButton(
                    //   icon: const Icon(Icons.menu, color: Colors.white),
                    //   onPressed: _showMenu,
                    //   tooltip: '菜单',
                    //   iconSize: 18,
                    //   padding: const EdgeInsets.symmetric(horizontal: 12),
                    //   splashRadius: 20,
                    // ),

                    // 置顶按钮
                    IconButton(
                      icon: Icon(
                        _isAlwaysOnTop ? Icons.push_pin : Icons.push_pin_outlined,
                        color: Colors.white,
                      ),
                      onPressed: _toggleAlwaysOnTop,
                      tooltip: _isAlwaysOnTop ? '取消置顶' : '置顶',
                      iconSize: 18,
                      padding: const EdgeInsets.symmetric(horizontal: 12),
                      splashRadius: 20,
                    ),

                    // 最小化按钮
                    MinimizeWindowButton(
                      colors: WindowButtonColors(
                        iconNormal: Colors.white,
                        mouseOver: Colors.blue[600],
                        mouseDown: Colors.blue[800],
                        iconMouseOver: Colors.white,
                        iconMouseDown: Colors.white70,
                      ),
                      onPressed: appWindow.minimize,
                    ),

                    // 最大化/还原按钮
                    MaximizeWindowButton(
                      colors: WindowButtonColors(
                        iconNormal: Colors.white,
                        mouseOver: Colors.blue[600],
                        mouseDown: Colors.blue[800],
                        iconMouseOver: Colors.white,
                        iconMouseDown: Colors.white70,
                      ),
                      onPressed: appWindow.maximizeOrRestore,
                    ),

                    // 关闭按钮
                    CloseWindowButton(
                      colors: WindowButtonColors(
                        iconNormal: Colors.white,
                        mouseOver: Colors.red,
                        mouseDown: Colors.red[700],
                        iconMouseOver: Colors.white,
                        iconMouseDown: Colors.white70,
                      ),
                      onPressed: appWindow.close,
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),

        Expanded(child: Row(children: [if (!isSmallScreen) _LeftSidebar(controller: _controller), Expanded(child: Center(child: _ScreensExample(controller: _controller)))])),
      ]),
    );
  }
}

// Icons.cached              // 缓存(循环箭头)
// Icons.handover            // 交接
// Icons.schedule            // 时间安排
// Icons.access_time         // 访问时间
// Icons.watch_later         // 稍后查看

class _LeftSidebar extends StatelessWidget {
  _LeftSidebar({
    required SidebarXController controller,
  }) : _controller = controller;

  final SidebarXController _controller;
  final shiftProvider = Get.find<TurnShiftProvider>();

  @override
  Widget build(BuildContext context) {
    return SidebarX(
      controller: _controller,
      theme: SidebarXTheme(
        // 设置侧边栏背景装饰，包括背景色和圆角
        decoration: BoxDecoration(color: canvasColor, borderRadius: BorderRadius.circular(0)),
        // 设置鼠标悬停时的背景色
        // hoverColor: scaffoldBackgroundColor,
        // 设置
        hoverIconTheme: const IconThemeData(color: accentCanvasColor, size: 20),
        // 设置普通状态下的文本样式
        textStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
        // 设置选中状态下的文本样式
        selectedTextStyle: const TextStyle(color: Colors.white),
        // 设置鼠标悬停时的文本样式
        hoverTextStyle: const TextStyle(color: accentCanvasColor, fontWeight: FontWeight.w500),
        // 设置普通状态下的文本内边距
        itemTextPadding: const EdgeInsets.only(left: 14),
        // 设置选中状态下的文本内边距
        selectedItemTextPadding: const EdgeInsets.only(left: 14),
        // 设置普通状态下的项装饰样式
        itemDecoration: BoxDecoration(borderRadius: BorderRadius.circular(10), border: Border.all(color: canvasColor)),
        // 设置选中状态下的项装饰样式，包括边框、渐变背景和阴影效果
        selectedItemDecoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
            border: Border.all(color: actionColor.withOpacity(0.37)),
            gradient: const LinearGradient(colors: [accentCanvasColor, canvasColor]),
            boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.28), blurRadius: 4)]),
        // 设置普通状态下的图标主题
        iconTheme: IconThemeData(color: Colors.white.withOpacity(0.7), size: 20),
        // 设置选中状态下的图标主题
        selectedIconTheme: const IconThemeData(color: Colors.white, size: 20),
      ),
      extendedTheme: const SidebarXTheme(width: 100, decoration: BoxDecoration(color: canvasColor)),
      // footerDivider: divider,
      headerBuilder: (context, extended) {
        return const SizedBox(height: 20, child: Padding(padding: EdgeInsets.all(6.0)));
      },
      items: [
        const SidebarXItem(icon: Icons.home, label: '收银'),
        const SidebarXItem(icon: Icons.local_gas_station, label: '实况'),
        const SidebarXItem(icon: Icons.format_list_bulleted, label: '订单'),
        const SidebarXItem(icon: Icons.people_outline_outlined, label: '会员'),
        SidebarXItem(icon: Icons.settings, label: '设置', onLongPress: () => showLogViewer(context)),
      ],
      footerItems: [
        SidebarXItem(icon: Icons.more_time, label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.people_outline_outlined, label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.supervisor_account , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.flash_on  , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.bolt   , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.water_drop   , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.waves    , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.oil_barrel     , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.videocam , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.precision_manufacturing , label: '交班', selectable: false, onTap: () => shiftProvider.clickTurnOver()),
        // SidebarXItem(icon: Icons.exit_to_app, label: '退出', onTap: () => debugPrint('Exit')),
      ],
    );
  }

  void _showDisabledAlert(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Item disabled for selecting',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.redAccent,
      ),
    );
  }

  // 使用示例
  void showLogViewer(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) {
        return const LogViewerDialog();
      },
    );
  }

}

class _ScreensExample extends StatefulWidget {
  const _ScreensExample({
    required this.controller,
  });

  final SidebarXController controller;

  @override
  State<_ScreensExample> createState() => _ScreensExampleState();
}

class _ScreensExampleState extends State<_ScreensExample> {
  // 1. 创建 PageController 并与控制器关联
  late final PageController _pageController;
  late List<Widget> _pageList;

  @override
  void initState() {
    super.initState();

    _pageList = [
      const CashierPage(),
      // const OrderPage(),
      const GunLivePage(),
      // const WebPageWin(url: 'https://mp.hqtong.com/user/login'),
      // const GoodsPage(),
      // const StatisticsPage(),
      // const ShopPage(),
      const OrderPage(),
      // const DemoPage(),
      const MemberPage(),
      const SettingPage(),
      // TabHomeFragment(),
    ];
    _pageController = PageController(initialPage: widget.controller.selectedIndex);
    // 监听控制器变化，同步页面索引
    widget.controller.addListener(() {
      _pageController.jumpToPage(widget.controller.selectedIndex);
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 修复后的页面容器
        Expanded(
          child: PageView.builder(
            controller: _pageController, // 关键点：绑定控制器
            itemCount: _pageList.length, // 根据实际页面数量调整
            itemBuilder: (context, index) {
              // 2. 使用 GlobalKey 保持页面状态
              return GestureDetector(
                onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
                child: PageStorage(
                  bucket: PageStorageBucket(),
                  child: _pageList[index],
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}

String _getTitleByIndex(int index) {
  switch (index) {
    case 0:
      return '收銀';
    case 1:
      return '实况';
    case 2:
      return '会员';
    case 3:
      return 'Favorites';
    case 4:
      return 'Custom iconWidget';
    case 5:
      return 'Profile';
    case 6:
      return 'Settings';
    default:
      return 'Not found page';
  }
}

const primaryColor = Color(0xFF685BFF);
const canvasColor = Color(0xFF2E2E48);
const scaffoldBackgroundColor = Color(0xFF4B7EFE);
const accentCanvasColor = Color(0xFF4B7EFE);
const white = Colors.white;
final actionColor = const Color(0xFF5F5FA7).withOpacity(0.6);
final divider = Divider(color: white.withOpacity(0.3), height: 1);
